// main.dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'borrow_record.dart'; // 新增导入
import 'return_books.dart'; // 新增导入
import 'models.dart'; // 新增导入
import 'package:share_plus/share_plus.dart'; // 正确
import 'storage_service.dart'; // 确保有这个文件

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (kIsWeb) {
    await SharedPreferences.getInstance();
  }

  // 添加全局手势监听器（调试用）
  GestureBinding.instance.pointerRouter.addGlobalRoute((event) {
    print('全局点击事件: ${event.position}');
  });

  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: LibraryApp(),
      theme: appTheme,
      title: "校园图书馆",
    ),
  );
}

ThemeData appTheme = ThemeData(
  primaryColor: Colors.blue[800],
  secondaryHeaderColor: Colors.green[700],
);

int sel = 0;

// 更新为导入的类
final bodies = [
  HomeScreen(),
  BorrowList(), // 来自 borrow_record.dart
  ReturnScreen(), // 来自 return_books.dart
];

class LibraryApp extends StatefulWidget {
  LibraryApp({Key? key}) : super(key: key);

  @override
  _LibraryAppState createState() => _LibraryAppState();
}

class _LibraryAppState extends State<LibraryApp> {
  List<BottomNavigationBarItem> createItems() {
    return [
      BottomNavigationBarItem(
        icon: Icon(Icons.home_outlined),
        activeIcon: Icon(Icons.home, color: appTheme.primaryColor),
        label: "浏览图书",
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.list_alt_outlined),
        activeIcon: Icon(Icons.list_alt, color: appTheme.primaryColor),
        label: "借阅记录",
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.assignment_return_outlined),
        activeIcon: Icon(Icons.assignment_return, color: appTheme.primaryColor),
        label: "归还图书",
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('校园图书馆'),
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed:
                () => showSearch(
              context: context,
              delegate: BookSearchDelegate(),
            ),
          ),
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => AddBookPage()),
              );
            },
          ),
        ],
      ),
      body: bodies[sel],
      bottomNavigationBar: BottomNavigationBar(
        items: createItems(),
        currentIndex: sel,
        onTap: (index) => setState(() => sel = index),
        selectedItemColor: appTheme.primaryColor,
        unselectedItemColor: Colors.grey[600],
      ),
    );
  }
}

// 首页
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    if (allBooks.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.menu_book, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('暂无图书数据', style: TextStyle(fontSize: 18)),
            SizedBox(height: 8),
            Text('请添加图书或稍后再试', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    List<Book> computerScienceBooks = _getSafeSublist(0, 10);      // 计算机科学类（索引0-9）
    List<Book> literatureBooks = _getSafeSublist(10, 20);          // 文学类（索引10-19）
    List<Book> financeBooks = _getSafeSublist(20, 30);             // 金融经济类（索引20-29）
    List<Book> historyBooks = _getSafeSublist(30, 40);             // 历史类（索引30-39）
    List<Book> philosophyBooks = _getSafeSublist(40, 50);          // 哲学心理学类（索引40-49）
    List<Book> scienceBooks = _getSafeSublist(50, 60);             // 自然科学类（索引50-59）
    List<Book> artBooks = _getSafeSublist(60, 70);                // 艺术设计类（索引60-69）
    List<Book> medicalBooks = _getSafeSublist(70, 80);            // 医学健康类（索引70-79）
    return Scaffold(
    appBar: AppBar(title: Text('校园图书馆')),
    body: SingleChildScrollView(
      child: Column(
        children: [
          if (computerScienceBooks.isNotEmpty)
            _buildCategorySection('计算机科学', computerScienceBooks),
          if (literatureBooks.isNotEmpty)
            _buildCategorySection('文学', literatureBooks),
          if (financeBooks.isNotEmpty)
            _buildCategorySection('金融经济', financeBooks),
          if (historyBooks.isNotEmpty)
            _buildCategorySection('历史', historyBooks),
          if (philosophyBooks.isNotEmpty)
            _buildCategorySection('哲学心理学', philosophyBooks),
          if (scienceBooks.isNotEmpty)
            _buildCategorySection('自然科学', scienceBooks),
          if (artBooks.isNotEmpty)
            _buildCategorySection('艺术设计', artBooks),
          if (medicalBooks.isNotEmpty)
            _buildCategorySection('医学健康', medicalBooks),
          ],
        ),
      ),
    );
  }

  List<Book> _getSafeSublist(int start, int end) {
    if (start >= allBooks.length) return [];
    if (end > allBooks.length) end = allBooks.length;
    return allBooks.sublist(start, end);
  }

  Widget _buildCategorySection(String title, List<Book> books) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            title,
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
        ),
        SizedBox(
          height: 280,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: books.length,
            itemBuilder: (context, index) => BookCard(book: books[index]),
          ),
        ),
      ],
    );
  }
}

class BookCard extends StatefulWidget {
  final Book book;

  const BookCard({Key? key, required this.book}) : super(key: key);

  @override
  _BookCardState createState() => _BookCardState();
}


class _BookCardState extends State<BookCard> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 180,
      margin: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(color: Colors.black12, blurRadius: 4, spreadRadius: 1),
        ],
      ),
      child: Stack(
        children: [
          // 卡片主体内容（可点击查看详情）
          GestureDetector(
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => BookDetailPage(book: widget.book),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 封面图片
                _buildCoverImage(),

                // 图书信息
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.book.title,
                        style: TextStyle(fontWeight: FontWeight.bold),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      SizedBox(height: 4),
                      Text(
                        widget.book.author,
                        style: TextStyle(color: Colors.grey[600], fontSize: 12),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '可借: ${widget.book.availableCopies}',
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 借阅按钮（放在右上角，避免事件冲突）
          if (widget.book.availableCopies > 0)
            Positioned(
              top: 8,
              right: 8,
              child: ElevatedButton(
                onPressed: () {
                  print('🖱️ 借阅按钮被点击');
                  _borrowBook();
                },
                child: Text('借阅'),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  backgroundColor: Colors.blue[700],
                  foregroundColor: Colors.white,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildCoverImage() {
    print('加载封面: ${widget.book.coverUrl}'); // 调试信息
    
    return ClipRRect(
      borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
      child: Container(
        height: 180,
        width: double.infinity,
        color: Colors.grey[200],
        child: Center(
          child: widget.book.coverUrl.startsWith('http')
              ? Image.network(
                  widget.book.coverUrl,
                  height: 180,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    print('❌ 网络图片加载失败: ${widget.book.coverUrl}');
                    return _buildDefaultCover();
                  },
                )
              : Image.asset(
                  widget.book.coverUrl,
                  height: 180,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    print('❌ 本地资源加载失败: ${widget.book.coverUrl}');
                    return _buildDefaultCover();
                  },
                ),
        ),
      ),
    );
  }

  Widget _buildDefaultCover() {
    return Container(
      height: 180,
      color: Colors.grey[200],
      child: Icon(
        Icons.book,
        size: 60,
        color: Colors.grey[400],
      ),
    );
  }

  Future<void> _borrowBook() async {
    print('▶️ 开始借阅流程: ${widget.book.title}');

    // 减少可借数量
    setState(() {
      widget.book.availableCopies--;
    });
    print('📉 可借数量减少: ${widget.book.availableCopies}');

    final now = DateTime.now().toUtc();
    final dueDate = now.add(Duration(days: 30));

    final newRecord = BorrowRecord(
      bookId: widget.book.id,
      bookTitle: widget.book.title,
      borrowDate: now, // 使用UTC时间
      dueDate: dueDate, // 正确计算30天后
      isReturned: false,
    );

    print('📝 创建借阅记录: ${newRecord.bookTitle}');

    try {
      print('🔍 加载现有借阅记录...');
      List<List<dynamic>> records = [];

      final existingRecords = await StorageService.loadBorrowRecords();
      print('✅ 加载完成，记录数: ${existingRecords.length}');

      // 检查是否有标题行
      bool hasHeader = false;
      if (existingRecords.isNotEmpty) {
        records = existingRecords;
        hasHeader = records[0][0] == 'bookId';
        print(hasHeader ? '📋 发现标题行' : '⚠️ 未发现标题行');
      }

      // 如果没有标题行，添加标题行
      if (!hasHeader) {
        print('➕ 添加标题行');
        records.insert(0, ['bookId', 'bookTitle', 'borrowDate', 'dueDate', 'isReturned']);
      }

      // 添加新记录
      // 在 BookCard 的 _borrowBook 方法中
      // 添加新记录
      records.add([
        newRecord.bookId,
        newRecord.bookTitle,
        newRecord.borrowDate.toIso8601String(),
        newRecord.dueDate.toIso8601String(),
        newRecord.isReturned.toString(),
      ]);
      print('➕ 添加新记录，总记录数: ${records.length}');

      // 保存记录
      print('💾 开始保存借阅记录...');
      await StorageService.saveBorrowRecords(records);
      print('✅ 借阅记录保存成功!');

      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('✅ 已成功借阅《${widget.book.title}》')));
    } catch (e) {
      print('❌ 保存借阅记录失败: $e');
      setState(() {
        widget.book.availableCopies++;
      });
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('❌ 借阅失败: ${e.toString()}')));
    }
  }
}



class BookDetailPage extends StatelessWidget {
  final Book book;

  const BookDetailPage({Key? key, required this.book}) : super(key: key);

  void _shareBook(BuildContext context) {
    final text = '''
推荐书籍：《${book.title}》
作者：${book.author}
出版社：${book.publisher}
出版年份：${book.publishYear}

${book.description.length > 100 ? book.description.substring(0, 100) + '...' : book.description}

立即借阅，共享知识！''';

    Share.share(text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(book.title),
        actions: [
          IconButton(
            icon: Icon(Icons.share),
            onPressed: () => _shareBook(context),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 300,
              color: Colors.grey[200],
              child: Center(
                child:
                book.coverUrl.startsWith('http') ||
                    book.coverUrl.startsWith('data:image')
                    ? Image.network(book.coverUrl, fit: BoxFit.cover)
                    : Image.asset(book.coverUrl, fit: BoxFit.cover),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    book.title,
                    style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  Text(
                    '作者: ${book.author}',
                    style: TextStyle(fontSize: 18, color: Colors.grey[700]),
                  ),
                  Divider(height: 30),
                  Text('ISBN: ${book.isbn}'),
                  Text('出版社: ${book.publisher}'),
                  Text('出版年份: ${book.publishYear}'),
                  SizedBox(height: 20),
                  Text('图书简介:', style: TextStyle(fontWeight: FontWeight.bold)),
                  Text(book.description),
                  SizedBox(height: 30),
                  _buildStatusIndicator(),
                  SizedBox(height: 20),
                  if (book.availableCopies > 0)
                    Center(
                      child: ElevatedButton(
                        onPressed: () => _borrowBook(context),
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 32.0,
                            vertical: 16.0,
                          ),
                          child: Text('借阅此书', style: TextStyle(fontSize: 18)),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          book.availableCopies > 0 ? Icons.check_circle : Icons.cancel,
          color: book.availableCopies > 0 ? Colors.green : Colors.red,
        ),
        SizedBox(width: 8),
        Text(
          book.availableCopies > 0
              ? '可借阅 (${book.availableCopies}本可用)'
              : '已无库存',
          style: TextStyle(
            color: book.availableCopies > 0 ? Colors.green : Colors.red,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  void _borrowBook(BuildContext context) {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text('已成功借阅《${book.title}》')));
    Navigator.pop(context);
  }
}

class AddBookPage extends StatefulWidget {
  @override
  _AddBookPageState createState() => _AddBookPageState();
}

class _AddBookPageState extends State<AddBookPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _authorController = TextEditingController();
  final TextEditingController _isbnController = TextEditingController();
  final TextEditingController _publisherController = TextEditingController();
  final TextEditingController _yearController = TextEditingController();
  final TextEditingController _copiesController = TextEditingController(
    text: '1',
  );
  final TextEditingController _descriptionController = TextEditingController();

  Uint8List? _coverImageBytes;
  bool _isUploading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('添加新图书'),
        actions: [IconButton(icon: Icon(Icons.save), onPressed: _saveBook)],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              _buildCoverUploadSection(),
              SizedBox(height: 20),
              TextFormField(
                controller: _titleController,
                decoration: InputDecoration(
                  labelText: '书名*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.title),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入书名';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _authorController,
                decoration: InputDecoration(
                  labelText: '作者*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.person),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入作者';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _isbnController,
                decoration: InputDecoration(
                  labelText: 'ISBN',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.numbers),
                ),
              ),
              SizedBox(height: 16),
              Row(
                children: <Widget>[
                  Expanded(
                    child: TextFormField(
                      controller: _publisherController,
                      decoration: InputDecoration(
                        labelText: '出版社',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.business),
                      ),
                    ),
                  ),
                  SizedBox(width: 16),
                  Expanded(
                    child: TextFormField(
                      controller: _yearController,
                      decoration: InputDecoration(
                        labelText: '出版年份',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.calendar_today),
                      ),
                      keyboardType: TextInputType.number,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _copiesController,
                decoration: InputDecoration(
                  labelText: '数量*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.copy),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入数量';
                  }
                  if (int.tryParse(value) == null) {
                    return '请输入有效数字';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _descriptionController,
                decoration: InputDecoration(
                  labelText: '图书简介',
                  border: OutlineInputBorder(),
                  alignLabelWithHint: true,
                ),
                maxLines: 5,
              ),
              SizedBox(height: 32),
              ElevatedButton(
                onPressed: _saveBook,
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child:
                  _isUploading
                      ? CircularProgressIndicator(color: Colors.white)
                      : Text('保存图书', style: TextStyle(fontSize: 18)),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).primaryColor,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCoverUploadSection() {
    return Column(
      children: [
        Text(
          '图书封面',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 10),
        GestureDetector(
          onTap: _pickCoverImage,
          child: Container(
            height: 200,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(12),
            ),
            child:
            _coverImageBytes != null
                ? Image.memory(_coverImageBytes!, fit: BoxFit.cover)
                : Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.add_photo_alternate,
                    size: 50,
                    color: Colors.grey,
                  ),
                  SizedBox(height: 10),
                  Text(
                    '点击上传封面图片',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
            ),
          ),
        ),
        SizedBox(height: 10),
        if (_coverImageBytes != null)
          TextButton(onPressed: _pickCoverImage, child: Text('更换图片')),
      ],
    );
  }

  Future<void> _pickCoverImage() async {
    try {
      final pickedFile = await ImagePicker().pickImage(
        source: ImageSource.gallery,
        maxWidth: 800,
        maxHeight: 800,
        imageQuality: 85,
      );

      if (pickedFile != null) {
        final bytes = await pickedFile.readAsBytes();
        setState(() {
          _coverImageBytes = bytes;
        });
      }
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('选择图片失败: ${e.toString()}')));
    }
  }

  Future<void> _saveBook() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isUploading = true);

      String coverPath = 'assets/book_covers/default.jpg';

      if (_coverImageBytes != null) {
        // 对于Web平台，使用Base64编码
        final base64Image = base64Encode(_coverImageBytes!);
        coverPath = 'data:image/jpeg;base64,$base64Image';
      }

      final newBook = Book(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        title: _titleController.text,
        author: _authorController.text,
        coverUrl: coverPath,
        description: _descriptionController.text,
        isbn: _isbnController.text,
        publisher: _publisherController.text,
        publishYear: int.tryParse(_yearController.text) ?? DateTime.now().year,
        totalCopies: int.parse(_copiesController.text),
        availableCopies: int.parse(_copiesController.text),
      );

      allBooks.add(newBook);

      setState(() => _isUploading = false);

      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('《${newBook.title}》添加成功！')));

      Navigator.pop(context);
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _authorController.dispose();
    _isbnController.dispose();
    _publisherController.dispose();
    _yearController.dispose();
    _copiesController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }
}

class BookSearchDelegate extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    return [IconButton(icon: Icon(Icons.clear), onPressed: () => query = '')];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () => close(context, ''),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    final results = allBooks.where(
          (book) =>
      book.title.toLowerCase().contains(query.toLowerCase()) ||
          book.author.toLowerCase().contains(query.toLowerCase()),
    );

    return ListView.builder(
      itemCount: results.length,
      itemBuilder:
          (context, index) => ListTile(
        leading:
        results.elementAt(index).coverUrl.startsWith('http')
            ? Image.network(
          results.elementAt(index).coverUrl,
          width: 50,
        )
            : Image.asset(
          results.elementAt(index).coverUrl,
          width: 50,
        ),
        title: Text(results.elementAt(index).title),
        subtitle: Text(results.elementAt(index).author),
        onTap: () {
          close(context, '');
          Navigator.push(
            context,
            MaterialPageRoute(
              builder:
                  (context) =>
                  BookDetailPage(book: results.elementAt(index)),
            ),
          );
        },
      ),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestions =
    allBooks
        .where(
          (book) =>
      book.title.toLowerCase().contains(query.toLowerCase()) ||
          book.author.toLowerCase().contains(query.toLowerCase()),
    )
        .toList();

    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder:
          (context, index) => ListTile(
        title: Text(suggestions[index].title),
        subtitle: Text(suggestions[index].author),
        onTap: () {
          query = suggestions[index].title;
          showResults(context);
        },
      ),
    );
  }
}
